// pages/user/user.js
const app = getApp();

Page({
  data: {
    userInfo: {},
    genders: ['男', '女', '未知'], // 显示文本
    genderValues: [1, 2, 0],       // 实际保存的值（对应 myInfo 的 genderMap）
    genderText: '未知',
    birthday: ''
  },

  onLoad() {
    const userInfo = wx.getStorageSync('userInfo') || {};
    this.setData({
      userInfo: userInfo,
      genderText: this.data.genders[userInfo.gender] || '未知',
      birthday: userInfo.birthday || ''
    });
  },

  // 修改用户名
  updateNickName(e) {
    const newInfo = { ...this.data.userInfo, nickName: e.detail.value };
    this.setData({ userInfo: newInfo });
  },

  // 修改手机号
  updatePhone(e) {
    const newInfo = { ...this.data.userInfo, phone: e.detail.value };
    this.setData({ userInfo: newInfo });
  },

  // 修改头像
  changeAvatar() {
    wx.chooseImage({
      count: 1,
      success: res => {
        const newInfo = { ...this.data.userInfo, avatarUrl: res.tempFilePaths[0] };
        this.setData({ userInfo: newInfo });
      }
    });
  },

  // 修改性别
  changeGender(e) {
    const genderValue = this.data.genderValues[e.detail.value];
    const genderText = this.data.genders[e.detail.value];
    const newInfo = { ...this.data.userInfo, gender: genderValue };
    this.setData({
      userInfo: newInfo,
      genderText: genderText
    });
  },

  // 修改生日
  changeBirthday(e) {
    const newInfo = { ...this.data.userInfo, birthday: e.detail.value };
    this.setData({ userInfo: newInfo });
  },

  // 保存用户信息
  saveUserInfo() {
    const userInfo = this.data.userInfo;

    // 保存到本地存储
    wx.setStorageSync('userInfo', userInfo);

    // 更新全局数据
    if (app && app.globalData) {
      app.globalData.userInfo = userInfo;
    }

    // 显示保存成功提示
    wx.showToast({
      title: '保存成功',
      icon: 'success',
      success: () => {
        // 延迟 1 秒后返回上一页
        setTimeout(() => {
          wx.navigateBack();
        }, 1000);
      }
    });
  },

  // 退出登录
  logout() {
    wx.removeStorageSync('userInfo');
    wx.navigateBack();
  }
});